package com.music.note_android.ui.folder

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
import com.google.android.material.button.MaterialButton
import com.music.note_android.R
import com.music.note_android.data.model.Folder
import com.music.note_android.data.model.Note
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MoveNotesToFolderDialog : DialogFragment() {

    private val viewModel: FolderManagementViewModel by viewModels()
    
    private lateinit var recyclerViewFolders: RecyclerView
    private lateinit var recyclerViewNotes: RecyclerView
    private lateinit var tvSelectionCount: TextView
    private lateinit var btnCancel: MaterialButton
    private lateinit var btnConfirm: MaterialButton
    
    private lateinit var folderSelectionAdapter: FolderSelectionAdapter
    private lateinit var noteSelectionAdapter: NoteSelectionAdapter
    
    private var onNotesMovedToFolder: ((String, List<String>) -> Unit)? = null
    private var selectedFolderId: String? = null
    private val selectedNoteIds = mutableSetOf<String>()

    companion object {
        fun newInstance(onNotesMovedToFolder: (String, List<String>) -> Unit): MoveNotesToFolderDialog {
            return MoveNotesToFolderDialog().apply {
                this.onNotesMovedToFolder = onNotesMovedToFolder
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_move_notes_to_folder, null)
        
        initViews(view)
        setupAdapters()
        setupListeners()
        observeViewModel()
        
        // 加载数据
        viewModel.loadFolders()
        viewModel.loadAllNotes()
        
        return AlertDialog.Builder(requireContext())
            .setView(view)
            .create()
    }

    private fun initViews(view: View) {
        recyclerViewFolders = view.findViewById(R.id.recycler_view_folders)
        recyclerViewNotes = view.findViewById(R.id.recycler_view_notes)
        tvSelectionCount = view.findViewById(R.id.tv_selection_count)
        btnCancel = view.findViewById(R.id.btn_cancel)
        btnConfirm = view.findViewById(R.id.btn_confirm)
        
        // 初始状态下确认按钮不可用
        btnConfirm.isEnabled = false
    }

    private fun setupAdapters() {
        // 文件夹选择适配器
        folderSelectionAdapter = FolderSelectionAdapter { folder ->
            selectedFolderId = folder.id
            updateConfirmButtonState()
        }
        
        recyclerViewFolders.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = folderSelectionAdapter
        }
        
        // 笔记选择适配器
        noteSelectionAdapter = NoteSelectionAdapter { note, isSelected ->
            if (isSelected) {
                selectedNoteIds.add(note.id)
            } else {
                selectedNoteIds.remove(note.id)
            }
            updateSelectionCount()
            updateConfirmButtonState()
        }
        
        recyclerViewNotes.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = noteSelectionAdapter
        }
    }

    private fun setupListeners() {
        btnCancel.setOnClickListener {
            dismiss()
        }
        
        btnConfirm.setOnClickListener {
            selectedFolderId?.let { folderId ->
                if (selectedNoteIds.isNotEmpty()) {
                    onNotesMovedToFolder?.invoke(folderId, selectedNoteIds.toList())
                    dismiss()
                }
            }
        }
    }

    private fun observeViewModel() {
        // 观察文件夹列表
        lifecycleScope.launch {
            viewModel.folders.collect { folders ->
                folderSelectionAdapter.submitList(folders)
            }
        }
        
        // 观察笔记列表
        viewModel.allNotes.observe(viewLifecycleOwner) { notes ->
            noteSelectionAdapter.submitList(notes)
        }
    }

    private fun updateSelectionCount() {
        val count = selectedNoteIds.size
        tvSelectionCount.text = "已选择 $count 篇笔记"
    }

    private fun updateConfirmButtonState() {
        btnConfirm.isEnabled = selectedFolderId != null && selectedNoteIds.isNotEmpty()
    }
}